/*
 * Copyright 2013 The Scripps Research Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.scripps.fl.entrez.transformer;

import java.util.List;

import org.apache.commons.collections.Transformer;
import org.dom4j.Node;

public class PubMedTransformer implements Transformer { // <Node, String> {

	private int maxLength;

	public PubMedTransformer() {
		this(Integer.MAX_VALUE);
	}

	public PubMedTransformer(int maxLength) {
		this.maxLength = maxLength;
	}

	// public String transform(Node docSumNode) {
	public Object transform(Object obj) {
		Node docSumNode = (Node) obj;
		List<Node> authorNodes = docSumNode.selectNodes("Authors/Author/Name/text()");
		StringBuffer authors = new StringBuffer();
		for (Node node : authorNodes) {
			if (authors.length() > 0)
				authors.append(", ");
			authors.append(node.getText());

		}
		if (authors.length() > 0)
			authors.append(". ");
		String title = docSumNode.valueOf("Title/text()");
		String source = docSumNode.valueOf("Source/text()");
		String pubDate = docSumNode.valueOf("PubDate/text()");
		String volume = docSumNode.valueOf("Volume/text()");
		String issue = docSumNode.valueOf("Issue/text()");
		String pages = docSumNode.valueOf("Pages/text()");
		String label = formatLabel(authors.toString(), title, source, pubDate, volume, issue, pages);
		if (label.length() > maxLength & authorNodes.size() > 0)
			label = formatLabel(authorNodes.get(0).getText() + " et al. ", title, source, pubDate, volume, issue, pages);
		if (label.length() > maxLength)
			label = label.substring(1, maxLength - 3) + "...";
		return label;
	}

	protected String formatLabel(String authors, String title, String source, String pubDate, String volume, String issue, String pages) {
		StringBuffer label = new StringBuffer();
		label.append( String.format("%s%s %s %s; %s", authors, title, source, pubDate, volume) );
		if( ! "".equals(issue) )
			label.append(String.format("(%s)", issue));
		if( ! "".equals(pages) )
			label.append(String.format(" %s", pages));
		return label.toString();
	}
}